package es.mgil.whoWantsToBeAMillonaire.runnables;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Message;

import com.google.gson.GsonBuilder;

import es.mgil.whoWantsToBeAMillonaire.handlers.GetFriendsScoresHandler;
import es.mgil.whoWantsToBeAMillonaire.util.HighScoreList;

public class GetFriendsScoresRunnable implements Runnable {
	public static final int GET_FRIENDS_SCORES_ERROR_EMPTY = 0;
	public static final int GET_FRIENDS_SCORES_ERROR_SERVER = 1;
	public static final int GET_FRIENDS_SCORES_ERROR_NO_FRIENDS = 2;
	public static final int GET_FRIENDS_SCORES_OK = 3;

	private GetFriendsScoresHandler handler;
	private String name;

	public GetFriendsScoresRunnable(Context context, String name) {
		this.name = name;
		this.handler = new GetFriendsScoresHandler(context);
	}

	@Override
	public void run() {
		try {
			// create the parameters for the connection, indicating a timeout
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(params, 3000);
			HttpConnectionParams.setSoTimeout(params, 5000);

			// create the connection to the external service
			HttpClient client = new DefaultHttpClient(params);
			List<NameValuePair> pairs = new ArrayList<NameValuePair>();
			pairs.add(new BasicNameValuePair("name", name));
			HttpGet request = new HttpGet(
					"http://soletaken.disca.upv.es:8080/CMU/rest/highscores?"
							+ URLEncodedUtils.format(pairs, "utf-8"));
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				try {
					// read the response
					InputStream stream = entity.getContent();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(stream));
					StringBuilder sb = new StringBuilder();
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					reader.close();
					stream.close();
					String responseString = sb.toString();

					// convert the response to a JSON object and create the real
					// object from it
					JSONObject json = new JSONObject(responseString);
					HighScoreList list = new GsonBuilder().create().fromJson(
							json.toString(), HighScoreList.class);
					if (list.getScores().isEmpty()) {
						// if hasn't any friend...
						handler.sendMessage(Message.obtain(handler,
								GET_FRIENDS_SCORES_ERROR_NO_FRIENDS));
					} else {
						// if all worked fine
						handler.sendMessage(Message.obtain(handler,
								GET_FRIENDS_SCORES_OK, list));
					}
				} catch (JSONException e) {
					// an error occurred while parsing JSON text
					handler.sendMessage(Message.obtain(handler,
							GET_FRIENDS_SCORES_ERROR_NO_FRIENDS));
				}
			} else {
				// an error occurred while getting the response from the server
				handler.sendMessage(Message.obtain(handler,
						GET_FRIENDS_SCORES_ERROR_SERVER));
			}
		} catch (ClientProtocolException e) {
			// an error occurred while trying to connect to the server
			handler.sendMessage(Message.obtain(handler,
					GET_FRIENDS_SCORES_ERROR_SERVER));
		} catch (UnsupportedEncodingException e) {
			// an error occurred while trying to connect to the server
			handler.sendMessage(Message.obtain(handler,
					GET_FRIENDS_SCORES_ERROR_SERVER));
		} catch (IOException e) {
			// an error occurred while trying to connect to the server
			handler.sendMessage(Message.obtain(handler,
					GET_FRIENDS_SCORES_ERROR_SERVER));
		}
	}

	/**
	 * Get all the friend's scores of the user
	 */
	public void loadFriendsScores() {
		if (name.trim().equals("")) {
			// if the name is not set, don't retrieve nothing
			handler.sendMessage(Message.obtain(handler,
					GET_FRIENDS_SCORES_ERROR_EMPTY));
		} else {
			Thread thread = new Thread(this);
			thread.start();
		}
	}
}
